#include "sdf.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    void *deviceHandle = NULL;
    void *keyHandle = NULL;
    unsigned char iv[16] = {0}; // 假设IV为全零
    unsigned char plaintext[32] = "Hello, this is a test message!";
    unsigned char ciphertext[32] = {0};
    unsigned int ciphertextLen = 0;
    unsigned char decryptedtext[32] = {0};
    unsigned int decryptedtextLen = 0;

    // 打开设备
    if (SDF_OpenDevice(&deviceHandle) != SDR_OK) {
        printf("Failed to open device.\n");
        return 1;
    }

    // 获取设备信息
    DEVICEINFO deviceInfo;
    if (SDF_GetDeviceInfo(deviceHandle, &deviceInfo) != SDR_OK) {
        printf("Failed to get device info.\n");
        SDF_CloseDevice(deviceHandle);
        return 1;
    }
    printf("Device Name: %s\n", deviceInfo.DeviceName);

    // 生成随机数作为密钥
    unsigned char key[32];
    SDF_GenerateRandom(deviceHandle, sizeof(key), key);

    // 模拟创建密钥句柄
    keyHandle = malloc(sizeof(void*)); // 分配密钥句柄

    // 加密
    if (SDF_Encrypt(deviceHandle, keyHandle, 1, iv, plaintext, sizeof(plaintext), ciphertext, &ciphertextLen) != SDR_OK) {
        printf("Encryption failed.\n");
        SDF_CloseDevice(deviceHandle);
        return 1;
    }

    // 将加密数据写入c.bin
    FILE *fp = fopen("c.bin", "wb");
    if (fp == NULL) {
        printf("Failed to open c.bin for writing.\n");
        free(keyHandle);
        SDF_CloseDevice(deviceHandle);
        return 1;
    }
    fwrite(ciphertext, 1, ciphertextLen, fp);
    fclose(fp);

    // 解密
    if (SDF_Decrypt(deviceHandle, keyHandle, 1, iv, ciphertext, ciphertextLen, decryptedtext, &decryptedtextLen) != SDR_OK) {
        printf("Decryption failed.\n");
        free(keyHandle);
        SDF_CloseDevice(deviceHandle);
        return 1;
    }

    // 将解密数据写入message.txt
    fp = fopen("message.txt", "w");
    if (fp == NULL) {
        printf("Failed to open message.txt for writing.\n");
        free(keyHandle);
        SDF_CloseDevice(deviceHandle);
        return 1;
    }
    fwrite(decryptedtext, 1, decryptedtextLen, fp);
    fclose(fp);

    // 打印结果
    printf("Plaintext: %s\n", plaintext);
    printf("Ciphertext: ");
    for (unsigned int i = 0; i < ciphertextLen; i++) {
        printf("%02x", ciphertext[i]);
    }
    printf("\n");
    printf("Decrypted text: %s\n", decryptedtext);

    // 清理
    free(keyHandle);
    SDF_CloseDevice(deviceHandle);

    return 0;
}
